package microarray;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;

import java.net.URL;
import java.util.HashMap;
import java.util.StringTokenizer;

import javax.jdo.annotations.Persistent;

import org.apache.tools.tar.TarInputStream;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.urlfetch.*;
import com.google.appengine.api.urlfetch.FetchOptions.Builder;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable
public class RawData  implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7163189127715991246L;
	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;
	
	@Persistent
	private HashMap<String, Double> values; 
	
	private Platform platform;
	
	public RawData(String sample, Platform platform) throws Exception
	{
		values = new HashMap<String, Double>(); 
		this.platform = platform;
		
		String urlString = "http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=ACC_HERE&targ=self&view=data&form=text ";
		
		urlString = urlString.replace("ACC_HERE", sample);
		URL url = new URL(urlString);
		
		FetchOptions fetch = Builder.allowTruncate();
		URLFetchService fs = URLFetchServiceFactory.getURLFetchService(); 
		
    	HTTPResponse resp = fs.fetch(new HTTPRequest( url, HTTPMethod.GET, fetch.allowTruncate().setDeadline(15.0)));
    	ByteArrayInputStream bytes = new ByteArrayInputStream(resp.getContent());
    	
    	TarInputStream is = new TarInputStream(bytes);
    	parseData(is);
	}
	
	private void parseData(InputStream in) throws Exception
	{
		BufferedReader r = new BufferedReader(new InputStreamReader(in));
		String line = r.readLine();
		while(line != "!sample_table_begin")
			line = r.readLine();
		
		values = new HashMap<String, Double>();
		
		while(line != null)
		{
			StringTokenizer tok = new StringTokenizer(line);
			String id = tok.nextToken();
			String gene = platform.getGene(id);
			Double val = Double.parseDouble(tok.nextToken());
			
			values.put(gene, val);
		}
	}

}
